package com.xxx.rpc.client;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import com.xxx.rpc.common.xml.Dubbo;
import com.xxx.rpc.common.xml.tems.Reference;

public class ProxyClientRegistryPostProcessor
		implements BeanDefinitionRegistryPostProcessor,ApplicationContextAware{

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		Dubbo dubbo = applicationContext.getBean(Dubbo.class);
		if (dubbo != null) {
			List<Reference> referenceList = dubbo.getReferenceList();
			for (Reference ref : referenceList) {
				Class<?> fieldClass = null;
				try {
					fieldClass = Class.forName(ref.getInterfaceClazz());
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				BeanDefinitionHolder holder = createBeanDefinition(fieldClass);
				System.out.println("创建成功:" + ref.getInterfaceClazz());
				// 将代理类的beanDefination注册到容器中
				BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
			}
		}
	}

	

	/**
	 * 生成fieldClass类型的BeanDefinition
	 * 
	 * @return
	 */
	private BeanDefinitionHolder createBeanDefinition(Class<?> fieldClass) {
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReferenceBeanFactory.class);
		String className = fieldClass.getName();
		// bean的name首字母小写，spring通过它来注入
		String beanName = StringUtils.uncapitalize(className.substring(className.lastIndexOf('.') + 1));
		// 给ProxyFactoryBean字段赋值
		builder.addPropertyValue("interfaceClass", fieldClass);
		return new BeanDefinitionHolder(builder.getBeanDefinition(), beanName);
	}


}
